package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 小视频业务处理层
 */
@Service
@Slf4j
public class VideoService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private VideoApi videoApi;


    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发布小视频
     */
    @CacheEvict(value = "videoList", allEntries = true)
    public void postSmallVideos(MultipartFile videoThumbnail, MultipartFile videoFile) {
        try {
            log.debug("************发布小视频了***********************");
            String originalFilename = videoThumbnail.getOriginalFilename();//获取原始文件名
            //a.将视频封面上传阿里云，得到图片url地址
            String picUrl = ossTemplate.upload(originalFilename, videoThumbnail.getInputStream());
            ///b.将视频存入fastdfs 得到url地址
            //获取文件后缀
            String videoFileName = videoFile.getOriginalFilename();
            String suffix = videoFileName.substring(videoFileName.lastIndexOf(".") + 1);
            StorePath storePath = fastClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffix, null);
            //得到文件存储url地址
            String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
            //c.将发布小视频相关地址等信息保存到小视频表
            Video video = new Video();
            video.setUserId(UserHolder.getUserId());//当前用户id
            video.setVid(111l);//随便指定一个值 防止后面app报null
            video.setText("探花短视频");
            video.setPicUrl(picUrl);//视频封面
            video.setVideoUrl(videoUrl);//视频地址  fastDFS地址
            videoApi.save(video);
        } catch (IOException e) {
            log.error("将视频封面上传阿里云失败了，哈哈哈。。。。");
            throw new TanHuaException(ErrorResult.uploadPicFail());
        }

    }

    /**
     * 小视频列表查询
     */
    @Cacheable(value = "videoList", key = "#page + '_' +  #pagesize")
    public PageResult<VideoVo> querySmallVideos(int page, int pagesize) {
        log.debug("************************小视频列表查询从数据库查询************************");
        //a.调用服务提供者分页查询视频列表数据
        PageResult<Video> pageResultVideo = videoApi.querySmallVideos(page, pagesize);
        if (pageResultVideo == null || pageResultVideo.getItems() == null || pageResultVideo.getItems().size() == 0) {
            return null;
        }
        //b.根据发布小视频的userId  查询userInfo得到用户信息
        List<Video> items = pageResultVideo.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video video : items) {
            VideoVo videoVo = new VideoVo();
            BeanUtils.copyProperties(video, videoVo);
            //查询用户信息
            UserInfo userInfo = userInfoApi.findByUserId(video.getUserId());
            BeanUtils.copyProperties(userInfo, videoVo);

            videoVo.setId(video.getId().toHexString());//小视频主键id
            videoVo.setCover(video.getPicUrl());//设置小视频封面
            videoVo.setSignature(video.getText());//签名
            videoVo.setHasLiked(0);//是否点赞 1：是 0：否
            //查询redis是否关注此用户
            if(redisTemplate.hasKey("followUser_"+UserHolder.getUserId()+"_"+video.getUserId())){
                videoVo.setHasFocus(1);//是否关注 1：是 0：否
            }else {
                videoVo.setHasFocus(0);//是否关注 1：是 0：
            }
            videoVoList.add(videoVo);
        }
        ///c.封装VO返回
        PageResult<VideoVo> videoVoPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResultVideo, videoVoPageResult);
        videoVoPageResult.setItems(videoVoList);
        return videoVoPageResult;
    }
    /**
     * 关注用户
     */
    public void userFocus(long followUserId) {
        Long userId = UserHolder.getUserId();
        //1.关注用户写入follow_user
        FollowUser followUser = new FollowUser();
        followUser.setUserId(userId);//当前登录用户id
        followUser.setFollowUserId(followUserId);//被关注用户id
        videoApi.followUser(followUser);

        //1.将关注记录写入redis
        redisTemplate.opsForValue().set("followUser_"+userId+"_"+followUserId,"true");
    }

    /**
     * 取消关注用户
     */
    public void userUnFocus(long followUserId) {

        Long userId = UserHolder.getUserId();
        //1.关注用户写入follow_user
        FollowUser followUser = new FollowUser();
        followUser.setUserId(userId);//当前登录用户id
        followUser.setFollowUserId(followUserId);//被关注用户id
        videoApi.unfollowUser(followUser);

        //1.将关注记录写入redis
        redisTemplate.delete("followUser_"+userId+"_"+followUserId);
    }
}
